/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject;

import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import ru.irenproject.store.AbstractThing;
import ru.irenproject.store.Stash;

import com.google.protobuf.ByteString;
import com.google.protobuf.Message;

public final class QuestionListSelection extends AbstractThing implements Visual {
  static QuestionListSelection create(QuestionListEditor editor) {
    QuestionListSelection res = editor.store().create(QuestionListSelection.class);
    res.prepare(editor);
    return res;
  }

  @Stash private UiProtos.QuestionListSelection.Builder $;

  @Inject QuestionListSelection() {}

  private void prepare(QuestionListEditor editor) {
    $.setQuestionListEditor(editor.id());
  }

  private QuestionListEditor questionListEditor() {
    return get($.getQuestionListEditor(), QuestionListEditor.class);
  }

  @Override public Message render() {
    QuestionListEditor ed = questionListEditor();
    UiProtos.QuestionListSelectionShape.Builder b = UiProtos.QuestionListSelectionShape.newBuilder();

    Map<ByteString, Integer> m = ed.questionList().getItemIdToIndexMap();
    for (ByteString itemId : ed.selectedItemIdList()) {
      b.addSelectedIndex(m.get(itemId));
    }

    return b.build();
  }

  void update() {
    markForRender();
  }

  void add(ByteString itemId) {
    $.addSelectedItem(itemId);
  }

  void addAll(Iterable<ByteString> itemIds) {
    $.addAllSelectedItem(itemIds);
  }

  void clear() {
    $.clearSelectedItem();
  }

  List<ByteString> list() {
    return $.getSelectedItemList();
  }

  int count() {
    return $.getSelectedItemCount();
  }

  ByteString get(int index) {
    return $.getSelectedItem(index);
  }
}
